import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class GlobalKeyWidget extends StatefulWidget {
  @override
  GlobalKeyWidgetState createState() => new GlobalKeyWidgetState();
}
///GlobalKey能够跨Widget访问状态。
class GlobalKeyWidgetState extends State<GlobalKeyWidget> {
  //定义了一个GlobalKey并传递给SwitcherWidget，然后我们便可以通过这个key拿到它所绑定的
  // SwitcherWidgetState并在外部调用SwitcherWidgetState的changeState方法改变状态了。
  GlobalKey<SwitcherWidgetState> _key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SwitcherWidget(
        key: _key,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _key.currentState.changeState();
        },
        child: Text('切换'),
      ),
    );
  }
}

//开关控件是一个单独的控件，如果我们要想在外部该变改控件的状态，我们就需要使用GlobalKey
class SwitcherWidget extends StatefulWidget {
  const SwitcherWidget({Key key}) : super(key: key);

  @override
  SwitcherWidgetState createState() => new SwitcherWidgetState();
}

class SwitcherWidgetState extends State<SwitcherWidget> {
  bool isActive = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: CupertinoSwitch(
            value: isActive,
            activeColor: Colors.blueAccent,
            onChanged: (bool currentStatus) {
              isActive = currentStatus;
              setState(() {});
            }),
      ),
    );
  }

  void changeState() {
    isActive = !isActive;
    setState(() {});
  }
}
